package com.gel.aiagent.controller;

import com.gel.aiagent.agent.MyManus;
import com.gel.aiagent.app.LoveApp;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

import java.io.IOException;

@RestController
@RequestMapping("/ai")
public class AiController {

    @Resource
    private LoveApp loveApp;
    @Resource
    private ToolCallback[] allTools;

    @Resource
    private ChatModel dashscopeChatModel;

    /*恋爱大师SEE流式接口*/
    @GetMapping(value = "/love_app/chat/sse",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> doChatWithLovAppSSE(String message, String chatId) {
        return loveApp.doChatByStream(message,chatId);
    }

    @GetMapping(value = "/love_app/chat/server_sent_event")
    public Flux<ServerSentEvent<String>>doChatWithLovAppServerSentEvent(String message, String chatId){
       return loveApp.doChatByStream(message,chatId)
                .map(data -> ServerSentEvent.builder(data).build());
    }

    @GetMapping(value = "/love_app/chat/sse_emitter")
    public SseEmitter doChatWithLovAppSseEmitter(String message, String chatId){
        // 创建一个超时时间较长的 SseEmitter
        SseEmitter sseEmitter = new SseEmitter();
        // 获取 Flux 响应式数据流并且直接通过订阅推送给 SseEmitter
        loveApp.doChatByStream(message,chatId)
                .subscribe(chunk->{
                    try {
                        sseEmitter.send(chunk);
                    } catch (IOException e) {
                        sseEmitter.completeWithError(e);
                    }
                },sseEmitter::completeWithError,sseEmitter::complete);
        return sseEmitter;
    }
    /*超级智能体*/
    @GetMapping(value = "agent/chat")
    public SseEmitter doChatWithAgent(String message){
        MyManus myManus=new MyManus(allTools,dashscopeChatModel);
        return myManus.runStream(message);
    }
}

